package com.tul.exercise.base.thread.exercise;

import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * 计算斐波那契数列和，并返回结果
 */
public class Eg3 {
    public static void main(String[] args) {

        // 结果
        ArrayList<Future<Integer>> results = new ArrayList<>();

        // 线程池
        ExecutorService service = Executors.newFixedThreadPool(20);

        // 提交任务
        for (int i = 0; i < 15; i++) {
            results.add(service.submit(new Fibonacci2(i)));
        }


        // 展示结果
        for (Future<Integer> future:results) {
            try {
                System.out.println("计算结果：" + future.get());
            } catch (InterruptedException e) {
                System.out.println(e);
            } catch (ExecutionException e) {
                System.out.println(e);
            } finally {
                service.shutdown();
            }

        }

    }
}

class Fibonacci2 implements Callable {
    private int n;

    public Fibonacci2(int n) {
        this.n = n;
    }

    /**
     * 根据n产生斐波那契数列的第n个数
     *
     * @param n n
     * @return 第n个数
     */
    private int fibonacci(int n) {
        if (n == 1 || n == 2) {
            return 1;
        } else {
            return fibonacci(n - 1) + fibonacci(n - 2);
        }
    }

    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i < n; i++) {

            sum += fibonacci(i+1);

        }
        return sum;
    }
}
